import React, { useEffect, useState } from "react";
import { Button, Col, Row, Space, Table, Drawer, Switch, Tag } from "antd";
import type { ColumnsType } from "antd/es/table";
import { categoryGet } from "@/api/course";
import { CategoryType } from "@/types/course";
import RoleForm from "./components/role-form";
import { roleBatchDel, roleGet } from "@/api/user";
import { RoleType } from "@/types/user";

const columns: ColumnsType<RoleType> = [
  {
    title: "角色ID",
    dataIndex: "objectId",
    key: "objectId",
    render: (id) => <a>{id}</a>,
  },
  {
    title: "角色名称",
    dataIndex: "roleName",
    key: "roleName",
  },
  {
    title: "角色权限",
    dataIndex: "permission",
    key: "permission",
    render: (checkedKeys) => {
      return (
        <>
          {checkedKeys.map((item: string) => {
            return <Tag key={item}>{item}</Tag>;
          })}
        </>
      );
    },
  },
  {
    title: "操作",
    key: "action",
    render: (_, record) => (
      <Space size="middle">
        <Button type="primary" size="small">
          编辑
        </Button>
        <Button type="primary" size="small" danger>
          删除
        </Button>
      </Space>
    ),
  },
];

const RoleList: React.FC = () => {
  const [open, setOpen] = useState(false);
  const [data, setData] = useState<Array<RoleType>>([]);
  const [selectedIds, setSelectedIds] = useState<React.Key[]>([]);
  useEffect(() => {
    roleGet().then((res) => {
      setData(res.data.results);
    });
  }, []);
  const onClose = () => {
    setOpen(false);
  };

  //配置表格可选
  const rowSelection = {
    onChange: (selectedRowKeys: React.Key[]) => {
      console.log(`selectedRowKeys: ${selectedRowKeys}`);
      setSelectedIds(selectedRowKeys);
    },
  };
  const handleBatchDel = () => {
    roleBatchDel(selectedIds).then(() => {
      let newData = data.filter((item) => !selectedIds.includes(item.objectId));
      setData(newData);
    });
  };

  return (
    <>
      <Row>
        <Col>
          <Button
            type="primary"
            onClick={() => {
              setOpen(true);
            }}
          >
            新增角色
          </Button>
          {selectedIds.length ? (
            <Button type="primary" danger onClick={handleBatchDel}>
              批量删除
            </Button>
          ) : (
            ""
          )}
        </Col>
      </Row>
      <Drawer
        title="Basic Drawer"
        placement="right"
        onClose={onClose}
        open={open}
      >
        <RoleForm />
      </Drawer>
      <Table
        rowSelection={{
          type: "checkbox",
          ...rowSelection,
        }}
        columns={columns}
        dataSource={data}
        rowKey="objectId"
      />
    </>
  );
};

export default RoleList;
